package com.zyy.java8.samples.stream;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

/**
 * @author zhangyiying
 * @ClassName: Streams7
 * @Description:
 * @date 2021/12/28 11:34
 */
public class Streams7 {

    static class Foo {
        String name;
        List<Bar> bars = new ArrayList<>();

        public Foo(String name) {
            this.name = name;
        }
    }

    static class Bar {
        String name;

        public Bar(String name) {
            this.name = name;
        }
    }


    public static void main(String[] args) {
//        test1();
        test2();
    }


    /**
     *  peek、map区别
     *  peek入参是Consumer，没有返回值
     *  map入参是Function，是需要返回值的
     *  当我们只需要对元素内部处理，使用peek是比较合适的，如果我们需要返回一个自定义的Stream时候，需要使用map
     *  一般peek在Debug场景使用比较方便
     *
     *  peek、foreach区别
     *  peek不会中断流，后面可以对流继续操作，foreach会中断流，只能进行遍历
     */
    static void test2(){
        IntStream
                .range(1,4)
                .mapToObj(num -> new Foo("Foo" + num))
                .peek(foo -> {
                    IntStream
                            .range(1,4)
                            .mapToObj(num -> new Bar( "Bar" + num + " <- " +foo.name))
                            .forEach(foo.bars::add);
                })
                .flatMap(foo -> foo.bars.stream())
                .forEach(bar -> System.out.println(bar.name));
    }

    static void test1() {
        List<Foo> foos = new ArrayList<>();

        IntStream
                .range(1, 4)
                .forEach(num -> foos.add(new Foo("Foo" + num)));

        foos.forEach(foo -> {
            IntStream
                    .range(1, 4)
                    .forEach(num -> foo.bars.add(new Bar("Bar" + num + " <- " + foo.name)));
        });

        foos
                .stream()
                .flatMap(foo -> foo.bars.stream())
                .forEach(bar -> System.out.println(bar.name));
    }
}
